package com.odais.UserManagement;

import java.util.HashMap;

import javax.xml.datatype.Duration;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.odais.R;
import com.odais.DataManagement.DataManager;
import com.odais.json.JSON_IO_Interface;

/**
 * 
 * @author LDC
 *
 * Characteristics :
 * - Log to server account / check validity
 * - Display popup for connecting informations (using saved user/pwd)
 * - Give UserID
 */

public class UserManager
{
// ===========================================================
// Constants
// ===========================================================
	private static final int MODE_WORLD_READABLE = 1;

// ===========================================================
// Fields
// ===========================================================
	private Context mContext;
	private static SharedPreferences myODAISOptions;
	private static SharedPreferences.Editor prefsEditor;
	public String UserLogin = null;
	public String UserPassword = null;
	
	private DataManager dataManager;
	
	private AlertDialog.Builder alert;
	private AlertDialog alertDialog;
	
	private EditText input1, input2;
	
	private boolean mIsLogged = false;
	
	private static String userID;
	
// ===========================================================
// Constructors
// ===========================================================
	public UserManager(Context context, DataManager dataMng)
	{
		mContext = context;
		UserLogin = new String();
		UserPassword = new String();
		dataManager = dataMng;

        myODAISOptions = mContext.getSharedPreferences("myODAISOptions", MODE_WORLD_READABLE);
	}
	

// ===========================================================
// Getter & Setter
// ===========================================================


	public static String getUserID() {
		userID = myODAISOptions.getString("odais_user_id", "ndef");
		return userID;
	}


	public static void setUserID(String userID) {
		
        prefsEditor = myODAISOptions.edit();
        prefsEditor.putString("odais_user_id", userID);
        prefsEditor.commit();
		UserManager.userID = userID;
	}


	// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
	public boolean Hello()
	{
		return true;//LogToServer();
	}
	
	
	private boolean LogToServer()
	{
		//Are we already logged?
		if(isLogged())
		{
			return true;
		}
		else
		{
			//Are there valid user/pwd saved?
			UserLogin = myODAISOptions.getString("odais_user_login", "ndef");
			UserPassword = myODAISOptions.getString("odais_user_password", "ndef");
//			if(UserLogin.equals("ndef") || UserLogin.equals("ndef")) //display popup
//			{
				//Popup
		        ShowLogginPopup();		
				
				//If connection successful, save these parameters        

//			}
//			else
//			{
//				//Silent connect ?? and welcome
//
//		        ShowLogginPopup();	
//		        //setLogged(true);
//				
//			}
 			return true;
		}
		
	}
	
	public boolean isLogged()
	{
		return mIsLogged;
	}
	
	private void setLogged(boolean logged)
	{
		mIsLogged = logged;
	}
	
	private boolean TryConnection(String user, String password)
	{
	    //Register it to ODAIS DB
	    String JSON_Buffer[] = new String[8];
	    HashMap<String, ?> JSON_BufferOut;
		//String JSON_BufferOut[];
		HashMap<String, String> datahash = new HashMap<String, String>();
		String TfResult = new String();
		
//		F94160587 = pwd
//		B14854894 = seller
//		A79800202 = customer

		JSON_Buffer[0] = "action";
		JSON_Buffer[1] = "update_password";
		JSON_Buffer[2] = "seller";
		JSON_Buffer[3] = user;
		JSON_Buffer[4] = "pwd";
		JSON_Buffer[5] = password;
//		JSON_Buffer[6] = "force";
//		JSON_Buffer[7] = "1";

		JSON_IO_Interface jsonPost = new JSON_IO_Interface();
		JSON_BufferOut = (HashMap<String, ?>) jsonPost.JSON_Post(JSON_Buffer, user, password);

		try {
			datahash = (HashMap<String, String>) JSON_BufferOut.get("0");
			TfResult = datahash.get("success").toString();
		} catch (Exception e) {
			e.printStackTrace();
			TfResult = "No valid response from server!";
		}
				
		if(TfResult=="true")
		{
			setLogged(true);
			return true;
		}
		else
		{
			setLogged(false);
			return false;
		}
	}
	
	public void ShowLogginPopup()
	{		        
		LayoutInflater factory = LayoutInflater.from(mContext);            
	    View textEntryView = factory.inflate(R.layout.userpwdpopup, null);
	
	    alert = new AlertDialog.Builder(mContext); 
	
	    alert.setTitle("Please Login"); 
	    alert.setMessage("Enter your email and password"); 
	    // Set an EditText view to get user input  
	    alert.setView(textEntryView); 
	    alert.setCancelable(false);
	    
	    alertDialog = alert.create();
	
	    
	    input1 = (EditText) textEntryView.findViewById(R.id.editPopupEmail);
	    input2 = (EditText) textEntryView.findViewById(R.id.editPopupPwd);
	    
	    if(!UserLogin.equals("ndef"))
	    	input1.setText(UserLogin);
	    
	    if(!UserPassword.equals("ndef"))
	    	input2.setText(UserPassword);
	    
	    final Button connectButton = (Button) textEntryView.findViewById(R.id.btLogin);
	
	    connectButton.setOnClickListener(new OnClickListener() { 
	    public void onClick(View v) { 
	    	String UserLoginText = input1.getText().toString();
	    	String UserPasswordText = input2.getText().toString();
			if(TryConnection(UserLoginText, UserPasswordText))
			{
				Toast.makeText(mContext, "Hello User " + UserLoginText, Toast.LENGTH_SHORT).show();

				setUserID(UserLoginText);
				
		        prefsEditor = myODAISOptions.edit();
		        prefsEditor.putString("odais_user_login", UserLoginText);
		        prefsEditor.putString("odais_user_password", UserPasswordText);
		        prefsEditor.commit();

		        dataManager.UpdateReservationList();

				alertDialog.dismiss();
			}
			else
			{
				Toast.makeText(mContext, "Wrong login or password", Toast.LENGTH_SHORT).show();
			}
	    }

	    }); 

		

	    alertDialog.show();
	}

}